using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Xml;
using My.IdlConverter.Core.Cfg;

namespace My.IdlConverter.Com
{
    public class ComGuidCenter
    {
        private static IDictionary<string, Guid> _guidTable = new Dictionary<string, Guid>();
        private static XmlDocument _doc = new XmlDocument();

        static ComGuidCenter()
        {
            _doc.Load(Configuration.GuidFile);
            XmlNodeList childNodes = _doc.SelectNodes("//Guids/Guid");
            foreach (XmlNode nextNode in childNodes)
            {
                XmlNode nameNode = nextNode.SelectSingleNode(".//Name");
                XmlNode valueNode = nextNode.SelectSingleNode(".//Value");
                Guid guid = new Guid(valueNode.InnerText);
                _guidTable.Add(nameNode.InnerText,guid);
            }
        }

        public static Guid Apply(string applier)
        {
            if (_guidTable.ContainsKey(applier))
            {
                return _guidTable[applier];
            }
            return Register(applier);
        }

        public static void Save()
        {
            _doc.Save(Configuration.GuidFile);
        }

        private static Guid Register(string applier)
        {
            Guid newId = Guid.NewGuid();
            _guidTable.Add(applier, newId);
            XmlNode parentNode = _doc.SelectSingleNode("//Guids");
            XmlNode guidNode = _doc.CreateElement("Guid");
            XmlNode nameNode = _doc.CreateElement("Name");
            nameNode.AppendChild(_doc.CreateTextNode(applier));
            XmlNode valueNode = _doc.CreateElement("Value");
            valueNode.AppendChild(_doc.CreateTextNode(newId.ToString()));
            guidNode.AppendChild(nameNode);
            guidNode.AppendChild(valueNode);
            parentNode.AppendChild(guidNode);
            return newId;
        }
    }
}
